﻿
using IDEAMS.core;
using IDEAMS.utils;
using log4net;
using System.IO;

namespace IDEAMS.model.dataAcquisition
{
    public class CollectDataCollection : SHCollection<CollectData>
    {
        private static ILog logger = LogManager.GetLogger(typeof(CollectDataCollection));

        public CollectDataCollection() { }

        public CollectDataCollection(CollectDataCollection collection)
        {
            collection.ForEach(x =>
            {
                CollectData data = new CollectData(x);
                dataList.Add(data);
                return false;
            });
        }

        public override bool Equals(CollectData obj, object key)
        {
            return (string)key == obj.name;
        }

        public override void CopyTo(CollectData src, CollectData dst)
        {
            dst.Copy(src);
        }

        public CollectDataCollection Clone()
        {
            return new CollectDataCollection(this);
        }

        public bool Save(string serialNo,ProcessStep step)
        {
            bool rn = true;
            rwLock.EnterReadLock();
            try
            {
                string dataPath = string.Format(TW_App.fileManager.collectDataPath, serialNo);
                if(!Directory.Exists(dataPath))
                {
                    Directory.CreateDirectory(dataPath);
                }
                string dataFile = string.Format(TW_App.fileManager.collectDataFile, serialNo ,(int)step);
                rn = XmlUtil.Save<CollectDataCollection>(dataFile, this);
            }
            finally
            {
                rwLock.ExitReadLock();
            }
            return rn;
        }

        public int Load(string serialNo,ProcessStep step)
        {
            int rn = -1;
            rwLock.EnterWriteLock();
            try
            {
                string dataFile = string.Format(TW_App.fileManager.collectDataFile, serialNo, (int)step);
                bool existsFlag = File.Exists(dataFile);
                if (!existsFlag)
                {
                    logger.WarnFormat("数据文件[{0}]不存在",dataFile);
                    return -2;
                }

                CollectDataCollection collection = XmlUtil.Load<CollectDataCollection>(dataFile);
                if(collection != null)
                {
                    dataList.Clear();
                    collection.ForEach(x =>
                    {
                        CollectData data = x.Clone();
                        dataList.Add(data);
                        return false;
                    });
                    rn = 0;
                }
                else
                {
                    logger.ErrorFormat("加载数据文件[{0}]失败", dataFile);
                    rn = -1;
                }
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
            return rn;
        }
    }
}
